import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Icon, Steps, Button, Form, Input, Dropdown, Menu, Divider, Alert } from 'antd'
import _ from 'lodash'
import 'styles/account.scss'
import Retrievekey from './retrievekey'
import Result from 'ant-design-pro/lib/Result'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { passportActions } from 'reduxs'
import { validRule } from 'services/utils'

const Step = Steps.Step
const FormItem = Form.Item

export default class EditEmail extends PureComponent {

  state = {
    current: 0
  }

  render () {
    const { onPressClose, user } = this.props
    const retrievekeyOpts = { mode: 'email', type: 'email', user }
    let currentView = [
      <Retrievekey 
        {...retrievekeyOpts}
        onPressNext={() => this.setState({ current: 1 })}
        />,
      <EditEmailForm 
        onPressNext={() => this.setState({ current: 2 })}
        />,
      <Result
        type="success"
        title="设置成功"
        description="结果已经提交到服务器，并且已经生效。"
        extra={(
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: 120 }}>
            <Button
              size="large"
              type="primary"
              style={{ width: 120, height: 42 }}
              onClick={onPressClose}
              >
              完成
            </Button>
          </div>
        )}
        style={{ width: '80%', marginTop: 120 }}
      />
    ]
    return (
      <div style={{ maxWidth: 1200, margin: 'auto' }}>
        <div style={{ textAlign: 'right' }}>
          <Icon 
            type="close" 
            style={{ fontSize: 30, cursor: 'pointer' }}
            onClick={onPressClose}
            />
        </div>
        <div style={{ margin: 'auto', width: 800, marginTop: 50 }}>
          <Steps current={this.state.current}>
            <Step title="验证身份" />
            <Step title="修改电子邮箱" />
            <Step title="完成" />
          </Steps>
          
          {currentView[this.state.current]}
        </div>
      </div>
    )
  }
}

@connect(
  state => ({
    editInfoPending  : state.Passport.editInfoPending,
    editInfoError    : state.Passport.editInfoError,
    editInfoMessage  : state.Passport.editInfoMessage,
    rules            : state.Passport.rules
  }),
  dispatch => ({
    actions: bindActionCreators({ ...passportActions }, dispatch)
  })
)
@Form.create()
class EditEmailForm extends PureComponent {

  static propTypes = {
    onPressNext: PropTypes.func
  }

  static defaultProps = {
    onPressNext: () => null
  }

  state = {
    alert: null
  }

  componentWillReceiveProps (nextProps) {
    const { editInfoError, editInfoMessage } = nextProps
    if (editInfoError !== this.props.editInfoError) {
      editInfoError === 0 && this.props.onPressNext()
      editInfoError > 0 && this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px 40px' }}
          message={editInfoMessage}
          type="error"
          showIcon
          key="aaa"
        />
      )})
    }
  }

  render () {
    const { onPressNext, form, editInfoPending, rules } = this.props
    const { getFieldDecorator } = form
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }
    return (
      <div>
        <Form
          className="account-form"
          style={{ margin: 'auto', marginTop: 80, width: 600 }}
          layout="horizontal" 
          onSubmit={this.handleSubmit}
          >
          {editInfoPending ? null : (
            <QueueAnim component="div" type={['bottom', 'top']} leaveReverse>
              {this.state.alert ? this.state.alert : null}
            </QueueAnim>
          )}
          <FormItem
            {...formItemLayout}
            label="电子邮箱"
            >
            {getFieldDecorator('email', {
              rules: [
                { required: true, message: '请输入电子邮箱!' },
                { validator: this.checkEmail.bind(this, rules['email']), message: '电子邮箱格式错误' },
              ],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            wrapperCol={{ span: 16, offset: 6 }}
            >
            <Button 
              type="primary" 
              htmlType="submit"
              style={{ width: 150, height: 36, marginTop: 10, backgroundColor: '#188fff', borderColor: '#1890ff' }}
              loading={editInfoPending}
              >
              确定
            </Button>
          </FormItem>
        </Form>
        <Divider dashed />
        <div style={{ margin: '0 60px'}}>
          <h2 style={{ fontSize: 15, marginBottom: 16 }}>修改电子邮箱</h2>
          <p style={{ lineHeight: 1.8, marginLeft: 20 }}>1、电子邮箱可用于登录、修改密码等等。</p>
        </div>
      </div>
    )
  }

  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.actions.editInfo(values)
      }
    })
  }

  checkEmail (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || 'E-Mail格式错误')
    }
    callback()
  }
}